package cn.wolfcode.mq.listener;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.mq.DefaultSendCallback;
import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMQResult;
import cn.wolfcode.mq.OrderMessage;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

@RocketMQMessageListener(
        consumerGroup = MQConstant.ORDER_PENDING_CONSUMER_GROUP,
        topic = MQConstant.ORDER_PENDING_TOPIC
)
@Component
@Slf4j
public class OrderPendingMessageListener implements RocketMQListener<OrderMessage> {

    private final IOrderInfoService orderInfoService;
    private final RocketMQTemplate rocketMQTemplate;

    public OrderPendingMessageListener(IOrderInfoService orderInfoService, RocketMQTemplate rocketMQTemplate) {
        this.orderInfoService = orderInfoService;
        this.rocketMQTemplate = rocketMQTemplate;
    }

    @Override
    public void onMessage(OrderMessage message) {
        log.info("[创建订单] 收到创建订单消息, 准备开始创建订单: {}", JSON.toJSONString(message));
        OrderMQResult result = new OrderMQResult();
        result.setToken(message.getToken());

        try {
            OrderInfo orderInfo = orderInfoService.doSeckill(message.getUserPhone(), message.getSeckillId(), message.getTime());
            result.setOrderNo(orderInfo.getOrderNo());
            // 订单创建成功
            result.setCode(Result.SUCCESS_CODE);
            result.setMsg("订单创建成功");

            // 当下单成功后, 发送一个延迟消息, 检查订单支付状态, 超过时间未支付, 就直接取消该订单
            message.setOrderNo(orderInfo.getOrderNo());
            Message<OrderMessage> orderMessage = MessageBuilder.withPayload(message).build();

            // private String messageDelayLevel = "1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h";
            rocketMQTemplate.asyncSend(MQConstant.ORDER_PAY_TIMEOUT_TOPIC, orderMessage,
                    new DefaultSendCallback("订单超时未支付检查"), 2000, MQConstant.ORDER_PAY_TIMEOUT_DELAY_LEVEL);
        } catch (Exception e) {
            // 订单创建失败
            result.setCode(SeckillCodeMsg.SECKILL_ERROR.getCode());
            result.setMsg(e.getMessage());
            // 回补 Redis 数量控制/删除用户下单标示/删除本地下单标识
            orderInfoService.failedRollback(message);
        }
        // 发送订单创建结果消息
        rocketMQTemplate.asyncSend(MQConstant.ORDER_RESULT_TOPIC, result, new DefaultSendCallback("订单结果"));
    }
}
